package com.ruipengkj.view.statementView;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;

import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.bean.TRole;
import com.ruipengkj.bean.TRoleRight;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.model.MemberQueryRoleModel;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TRightService;
import com.ruipengkj.service.TRoleRightService;
import com.ruipengkj.service.TRoleService;
import com.ruipengkj.view.base.BasePagePanel;
import com.ruipengkj.view.systemView.SystemManagePrivilegeAdd;
import com.ruipengkj.view.systemView.SystemManagePrivilegeEmpAddDialog;
import com.ruipengkj.view.systemView.SystemManagePrivilegeModify;
//集成分页组件
public class StatementRole extends BasePagePanel<TRole> implements Runnable{
		private static final long serialVersionUID = 1L;
		private JTable table;
		private MemberQueryRoleModel memberQueryRoleModel;
		private JScrollPane tableJsp;
		private TRoleService tRoleService;
		private JButton queryButton = null;//添加权限
		private JButton roleButton;//权限分配
		private JButton delButton;//删除
		private JButton addButton;//添加
		
		//private JCheckBox []jCheckBox;
		private SystemManagePrivilegeAdd systemManagePrivilegeAdd;//添加面板
		private TEmployeeService tEmployeeService;
		private TRightService tRightService;
		private TRoleRightService tRoleRightService;
		private StatementPermissions statementPermissions;
		private SystemManagePrivilegeModify systemManagePrivilegeModify;
		private SystemManagePrivilegeEmpAddDialog systemManagePrivilegeEmpAddDialog;//权限分配界面
		public StatementRole(StatementPermissions _statementPermissions) {
			statementPermissions = _statementPermissions;
			tRoleService=BuildSpringApplication.getInstance().getTRoleServiceImpl();
			tEmployeeService=BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
			tRightService=BuildSpringApplication.getInstance().getTRightServiceImpl();
			tRoleRightService=BuildSpringApplication.getInstance().getTRoleRightServiceImpl();
			this.setLayout(new BorderLayout());
			this.init();
			this.initListener();
		}
	
		public String getID(){
			String id=table.getValueAt(table.getSelectedRow(), -1).toString();
			
			return id;
		}
		
		private void init() {
			// TODO Auto-generated method stub
			memberQueryRoleModel=new MemberQueryRoleModel();
			table=uiFactory.createRPJTable(memberQueryRoleModel, null, this, 30, JLabel.CENTER);
			table.getSelectionModel().addListSelectionListener(new ListSelectionListener()
			{
				@Override
				public void valueChanged(ListSelectionEvent arg0) {
					System.out.print(arg0);
				}
				
			});
			//table设置列宽度 AUTO_RESIZE_SUBSEQUENT_COLUMNS 填满父容器  JTable.AUTO_RESIZE_OFF 自适应
			table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
//			tableJsp=new JScrollPane(table);
			tableJsp=uiFactory.createJScrollPane(table);
			//table.addMouseListener(this);
			this.add(this.topPanel(), BorderLayout.NORTH);
			this.add(tableJsp, BorderLayout.CENTER);
			//排序
			TableRowSorter<MemberQueryRoleModel> tableRowSorter = new TableRowSorter<MemberQueryRoleModel>(memberQueryRoleModel);  
			table.setRowSorter(tableRowSorter);
		}
		private void initListener() {
			// TODO Auto-generated method stub
			queryButton.addActionListener(this);
			roleButton.addActionListener(this);
			addButton.addActionListener(this);
			delButton.addActionListener(this);
		}
		private JPanel topPanel() {
			JPanel jp;
			//cardNumTF = new JLabelJTextFieldComponent("卡号：", 15);
			queryButton = new RPJButtonBlue("添加权限");
			roleButton=new RPJButtonGray("权限分配");
			addButton = new RPJButtonBlue("添加角色");
			delButton = new RPJButtonBlue("删除角色");
			roleButton.setEnabled(false);
			//jp.add(cardNumTF);
			jp = new JPanelFlowLayoutComponent(new Component[]{addButton,delButton,queryButton,roleButton}, FlowLayout.LEFT);
		//	jp.add(queryButton);
			return jp;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource()==queryButton){
				statementPermissions.actionPerformed(e);
			}
			else if(e.getSource()==roleButton){
				//权限分配
				int row=table.getSelectedRow();
				if(row!=-1){
					try {
						String id=(String)table.getValueAt(table.getSelectedRow(),-1);
	    				TRole role=tRoleService.getByIdService(id);
	    				if(role==null){
	    					JOptionPane.showMessageDialog(null, "不存在此权限");
	    					return;
	    				}
	    				systemManagePrivilegeEmpAddDialog=new SystemManagePrivilegeEmpAddDialog(null,"权限分配",true);
	    				systemManagePrivilegeEmpAddDialog.showDialog(role);
					}catch (Exception ee) {
						ee.printStackTrace();
					}
				}else{
					JOptionPane.showMessageDialog(null, "请先选择权限");
				}
			}else if(e.getSource()==addButton){
				//添加
				systemManagePrivilegeAdd=new SystemManagePrivilegeAdd(null,"添加角色",true);
				systemManagePrivilegeAdd.showDialog();
				if(systemManagePrivilegeAdd.isSuccess){
					this.termQuery(1);	
				}
			}else if(e.getSource()==delButton){
				//删除
				
				if(table.getSelectedRow()!=-1){
					if(table.getValueAt(table.getSelectedRow(), 1).toString().equals("超级管理员")){
						JOptionPane.showMessageDialog(null, "超级管理员不可被删除");
						return;
					}
					if(JOptionPane.showConfirmDialog(null, "是否删除选中项？")==0){
						String id=(String)table.getValueAt(table.getSelectedRow(),-1);
						try {
							TRole role=tRoleService.getByIdService(id);
							if(role!=null){
								//更新员工权限
								Set<TEmployee> set=role.getTEmployees();
								if(set!=null&&set.size()!=0){
									Iterator<TEmployee> it=set.iterator();
									while(it.hasNext()){
										TEmployee emp=it.next();
										emp.setTRole(null);
										tEmployeeService.modifyService(emp);
									}
								}
								//删除权限
								Set<TRoleRight> set2=role.getTRoleRights();
								if(set2!=null&&set2.size()!=0){
									Iterator<TRoleRight> it=set2.iterator();
									while(it.hasNext()){
										TRoleRight rr=it.next();
										tRoleRightService.deleteService(rr.getId());
									}
								}
								tRoleService.deleteService(role.getRoleID());
								JOptionPane.showMessageDialog(null, "操作成功");
								this.termQuery(1);
								return;
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						JOptionPane.showMessageDialog(null, "操作失败");
					}
				} else {
					JOptionPane.showMessageDialog(null, "请先选择需要删除的角色");
				}
			}
		}
			
		@Override
		public void run() {
			// TODO Auto-generated method stub
			this.termQuery(1);
		}
		//条件查询
		protected void termQuery(final int currentPage) {
			final TRole trole=new TRole();
			new Thread(){
				public void run(){
					try {
						SwingUtilities.invokeAndWait(new Runnable(){
							public void run()
							{
								tableJsp.getViewport().remove(table);
								tableJsp.getViewport().add(waitComponent);
							}
						});							
						List<TRole> pageModel=tRoleService.getRoleService(trole);
						if(pageModel!=null){
							Util.clearTableRowSorter(table);
							
							memberQueryRoleModel.setRowData(pageModel);
							SwingUtilities.invokeLater(new Runnable() {
								@Override
								public void run() {
									tableJsp.getViewport().remove(waitComponent);
									tableJsp.getViewport().add(table);
									Util.setJTabelAutoClumnWidth(table);
//									pagingComponent.show();
								}
							});
						}else{
							//没有优惠卷信息
							tableJsp.getViewport().remove(waitComponent);
							tableJsp.getViewport().add(table);
							memberQueryRoleModel.clear();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
		
		public void setRoleSelectChangeListener(MouseListener _listener)
		{
			table.addMouseListener(_listener);
			
		}
		public void setLeftListener(ListSelectionListener e){
			table.getSelectionModel().addListSelectionListener(e);
		}	
		@Override
		public void mouseClicked(MouseEvent e) {			
	    	if(e.getSource()==table){
	    		//JOptionPane.showMessageDialog(null, "aaaaaaaaaaaa");
	    		roleButton.setEnabled(true);
	    		//表格
	    		if(e.getClickCount() == 2){
	    			
	    			if(table.getValueAt(table.getSelectedRow(), 1).toString().equals("超级管理员")){
	    				JOptionPane.showMessageDialog(null, "超级管理员不可被修改");
	    				return;
	    			}
	    			//修改商品
	    			String id=(String)table.getValueAt( table.getSelectedRow(),-1);
	    			try {
	    				TRole role=tRoleService.getByIdService(id);
	    				if(role==null){
	    					JOptionPane.showMessageDialog(null, "不存在此权限");
	    					return;
	    				}
	    				systemManagePrivilegeModify=new SystemManagePrivilegeModify(null,"修改角色",true);
	        			systemManagePrivilegeModify.showDialog(role);
	        			if(systemManagePrivilegeModify.isSuccess){
	        				this.termQuery(1);	
	        			}
					} catch (Exception e1) {
						e1.printStackTrace();
					}
	    		}
	    	}
	    	
		}

		@Override
		public void clear() {
			// TODO Auto-generated method stub
			
		}
}
